import { boot } from "quasar/wrappers";
import axios from "axios";
import { Notify } from "quasar";
// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({ baseURL: "https://api.example.com" });

api.interceptors.response.use(
  function (response) {
    // 数据处理
    return response;
  },
  function (error) {
    // 错误提示
    console.log("接口调用异常", error.config.url, error);
    Notify.create({
      type: "negative",
      message: `${error.config.url}：${error.message}`,
      position: "top",
      timeout: 3000,
    });
    return Promise.reject(error);
  }
);

// 创建一个专门调用用户的axios
const userApi = axios.create({ baseURL: "https://api.example.com" });

userApi.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("Authorization")) {
      config.headers.Authorization =
        "Basic " + localStorage.getItem("Authorization");
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

userApi.interceptors.response.use(
  function (response) {
    // 数据处理
    return response;
  },
  function (error) {
    // 错误提示
    console.log("接口调用异常", error);
    Notify.create({
      type: "negative",
      message: `${error.config.url}：${error.message}`,
      position: "top",
      timeout: 3000,
    });
    return Promise.reject(error);
  }
);

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios;
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api;
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
});

export { api, userApi };
